from redis import Redis

from hashlib import md5
from random import randint

import json
import time



def get_time():
    return int(time.time() % 1e6 )


class RedisSession:
    def __init__(self, table):
        self.session = Redis()
        self.table = table
        self.session.delete(table)

    def get(self, key):
        redis_val = self.session.hget(self.table, key)
        if redis_val is None:
            return None
        else:
            return json.loads(redis_val)

    def set(self, key, val):
        redis_val = json.dumps(val)
        self.session.hset(self.table, key, redis_val)

    def pop(self, key):
        self.session.hdel(self.table, key)

    def __iter__(self):
        for key in self.session.hkeys(self.table):
            yield key


def create_token(username):
    code = username + str(get_time()) + str(randint(12768, 25535))
    m = md5()
    m.update(code)
    return m.hexdigest()


if __name__ == '__main__':
    print(create_token('finley'))
    redis_session = RedisSession('test')
    redis_session.set('a', '1')
    print(redis_session.get('a'))
    for key in redis_session:
        print (key)
    redis_session.pop('a')
    print(redis_session.get('a'))

